package psico_test.utils.file;

import java.io.File;
import java.util.Vector;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

public class FileManager 
{
	private static FileManager instance;
	private static String path = System.getProperty("user.home")+"/Psico-Test";

	private FileManager()
	{
		new File(path).mkdir();
		new File(path+"/Experimentos").mkdir();
		new File(path+"/Resultados").mkdir();
		new File(path+"/Usuarios").mkdir();
		new File(path+"/Sonidos").mkdir();
		
		//importarExperimentos();
	}

	public static FileManager getInstance()
	{
		if(instance == null)
			instance = new FileManager();
		return instance;
	}

	public void importarExperimentos() 
	{
		int opcion = JOptionPane.showOptionDialog(null,"¿Desea importar Experimentos a la carpeta correspondiente?"
				,"Importación",JOptionPane.YES_OPTION,JOptionPane.QUESTION_MESSAGE,
				new javax.swing.ImageIcon(Class.class.getClass().getResource("/resources/explorar.png"))
				,new Object[]{"Sí","No"},"Si");
		
		if(opcion == 0)
		{
			JFileChooser jfc = new JFileChooser(System.getProperty("user.home"));
			jfc.setFileFilter(new XMLExtensionFileFilter());
			jfc.setMultiSelectionEnabled(true);
			if(jfc.showDialog(null,"Importar") == JFileChooser.APPROVE_OPTION)
			{
				File [] experimentos = jfc.getSelectedFiles();
				for(int i=0; i<experimentos.length;i++)
					experimentos[i].renameTo(new File(path+"/Experimentos/"+experimentos[i].getName()));
			}
		}
	}

	public synchronized File abrirArchivo()
	{
		JFileChooser jfc = new JFileChooser(path+"/Experimentos");
		jfc.setFileFilter(new XMLExtensionFileFilter());
		jfc.setMultiSelectionEnabled(false);
		int boton = jfc.showOpenDialog(null);
		if(boton == JFileChooser.APPROVE_OPTION)
		{
			File archivo = jfc.getSelectedFile();
			if(archivo.getAbsolutePath().toLowerCase().endsWith(".xml"))
				return jfc.getSelectedFile();
			else
				JOptionPane.showMessageDialog(null,"Error, no ha escogido un archivo XML");
		}
		System.out.println("va a devolver null");
		return null;
	}

	public synchronized File guardarArchivo()
	{
		JFileChooser jfc = new JFileChooser(path);
		jfc.setFileFilter(new XMLExtensionFileFilter());
		jfc.setMultiSelectionEnabled(false);
		int seleccion = jfc.showSaveDialog(null);
		if (seleccion == JFileChooser.APPROVE_OPTION)
		{
			File fichero = jfc.getSelectedFile();
			return fichero;
		}
		return null;
	}

	public Vector getSonidos()
	{
		Vector sonidos = new Vector();
		File[] aux = new File(path+"/Sonidos").listFiles(new SoundExtensionsFileFilter());
		for(int i=0; i<aux.length;i++)
		{
			if(aux[i].getAbsolutePath().endsWith(".mp3") || aux[i].getAbsolutePath().endsWith(".wav"));
			sonidos.add(aux[i]);
		}
		return sonidos;
	}
}
